<template>
  <div class="pdfBox" @contextmenu="oncontextmenu">
    <div class="pdfTitle">
      <div>
        <el-button @click="bigClick" :disabled="disabledBig"> 放大 </el-button>
        <el-button @click="littleClick" :disabled="disabledLittle">
          缩小
        </el-button>
        <el-button @click="serachClass" style="margin-left: 24px">
          查看下一个课件
        </el-button>

        <el-button @click="addexam" style="display: none; margin-left: 24px">
          完成学时
        </el-button>
      </div>
      <div
        style="
          color: #f00;
          font-size: 18px;
          flex: 1;
          display: flex;
          justify-content: space-between;
          padding:0 48px;
          align-items: center;
        "
      >
        提示: 培训课件需观看10分钟以上计算学时 (观看过程中,请勿刷新页面) 
        <p style="padding:0 10px;font-weight: 600;color:#000;font-size:22px;margin:0;" v-if="600 - timeNow - isTime>0">
          {{(600 - timeNow - isTime)/60>=10?'':'0'}}{{parseInt((600 - timeNow - isTime)/60)
          }}:{{(600 - timeNow - isTime)%60>=10?'':'0'}}{{(600 - timeNow - isTime)%60}}</p>
        <p style="padding:0 10px;font-weight: 600;color:#f00;font-size:22px;margin:0;" v-else>已看完</p>
      </div>
    </div>
    <div
      class="border"
      v-infinite-scroll="load"
      :infinite-scroll-disabled="disabled"
      :style="{ width: widthNum + '%' }"
      ref="bodyauto"
    >
      <pdf
        ref="pdf"
        :src="url"
        v-for="i in numPages"
        :key="i"
        :page="i"
        v-loading="loading"
      ></pdf>
    </div>
    <div
      style="
        position: absolute;
        top: 0;
        right: 0;
        height: 100vh;
        width: 100vw;
        z-index: 100000000;
      "
      v-if="disFace"
    >
      <face :comments="true" :show.sync="disFace" type="kjface"></face>
    </div>
  </div>
</template>

<script>
import pdf from "vue-pdf";
import { materialaddlog, materiallearnlog,materialList } from "@/api/admin.js";
import { getapplyid, setisTime, getisTime } from "@/utils/auth";
import { mapGetters } from "vuex";
import face from "@/components/PcFace";
export default {
  components: { pdf, face },
  computed: { ...mapGetters(["Jurisdictions", "initObj"]) },
  data() {
    return {
      url: "",
      id: this.$route.query.id,
      subjctid: this.$route.query.subjctid,
      numPages: 5,
      pagenum: 10,
      disabled: false,
      widthNum: 100,
      loading: false,
      disabledBig: true,
      disabledLittle: false,
      isTime: 0, //当前看了多久
      overTime: 0, //是否已经看完
      timeNow: 0, //之前看了多久
      Interval: Object,
      val: 0,
      goback: Object,
      facetimeObj: Object,
      disFace: false,
      isjj:true,
    };
  },
  watch: {
    disFace(val) {
      this.$nextTick(() => {
        if (val) {
          clearTimeout(this.facetimeObj);
        } else {
          if (
            this.initObj.is_face &&
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
              "开启" &&
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime
          ) {
            if (
              Number(JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                .kjfacetime)
            ) {
              this.facetimeObj = setTimeout(() => {
                this.disFace = true;
              }, JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime * 60 * 10);
            }
          }
          // this.$refs.time.start()
        }
      });
    },
    // isTime(val){
    //   if(val+this.timeNow >= 600){
    //     this.addLog()
    //     clearInterval(this.Interval);
    //   }
    // }
  },
  created() {
    setTimeout(() => {
      if (
        this.initObj.is_face &&
        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
          "开启" &&
        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime
      ) {
        if (
          navigator.getUserMedia ||
          (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
        ) {
          if(Number(JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                .kjfacetime)){
                  this.facetimeObj = setTimeout(() => {
                    this.disFace = true;
                  }, JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime * 60 * 10);
          }
        } else {
          this.$alert("该电脑没有摄像头，无法使用该模块", "提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.$router.go(-1);
            },
          });
        }
      }
    }, 1000);

    clearTimeout(this.goback);
    this.val = 2;
    // this.url = process.env.NODE_ENV === 'development'?"/api"+this.$route.query.pdf.split('.com')[1]:this.$route.query.pdf
    this.url = this.$route.query.pdf;
    this.getNumPages();
    this.jlLog();
    // if (
    //   getisTime() &&
    //   new Date().getSeconds - JSON.parse(getisTime()).time < 5
    // ) {
    //   this.isTime = JSON.parse(getisTime()).isTime;
    //   this.addLog();
    // }
  },
  methods: {
    async getNumPages() {
      let loadingTask = pdf.createLoadingTask(this.url);
      this.loading = true;
      await loadingTask.promise
        .then((pdf) => {
          this.loading = false;
          this.pagenum = pdf.numPages;
        })
        .catch((err) => {
          console.error("pdf 加载失败", err);
        });
    },
    //无限滚动
    load() {
      if (this.numPages + 1 > this.pagenum) {
        this.disabled = true;
      } else {
        this.disabled = false;
        this.numPages += 1;
      }
    },
    //查看下一个课件
    serachClass(){
      this.loading=true
      
      materialList({
        msid: this.subjctid,
        file_type: "课件",
        page: 1,
        limit: 10000,
        applyid: getapplyid(),
      }).then(async res=>{
        this.loading=false
        if(res.code==200){
          // this.pdfOffIn=res.data.list
          for (let index = 0; index < res.data.list.length; index++) {
            const item = res.data.list[index];
            if(item.id==this.id){
              if(index+1 >= res.data.list.length){
                this.$message.error('已是最后一个课件!!!');
                break
              }else{
                await this.addLog()
                this.isjj=true
                this.id=res.data.list[index+1].id
                this.url=res.data.list[index+1].file_path
                this.jlLog()
                break
              }
            }
          }
        }
      })
    },
    //禁止右键
    oncontextmenu(e) {
      e.preventDefault();
    },
    // 放大
    bigClick() {
      // console.log(this.widthNum)
      this.disabledLittle = false;
      if (this.widthNum != 100) {
        this.disabledBig = false;
        this.widthNum += 10;
        if (this.widthNum == 100) {
          this.disabledBig = true;
        }
      }
    },
    // 缩小
    littleClick() {
      // console.log(this.widthNum)
      this.disabledBig = false;
      if (this.widthNum != 20) {
        this.widthNum -= 10;
        this.disabledLittle = false;
        if (this.widthNum == 20) {
          this.disabledLittle = true;
        }
      }
    },
    //保存
    async addLog() {
      this.isjj=false
      if (this.timeNow + this.isTime >= 600) {
        this.overTime = 1;
      } else {
        this.overTime = 0;
      }
      let obj = {
        mid: this.id,
        msid: this.subjctid,
        period: this.isTime,
        done: this.overTime,
        applyid: getapplyid(),
        mprogress: '1',
      };
      // console.log(obj,'6666445566');
      await materialaddlog(obj).then((res) => {});
    },
    //获取学习记录
    async jlLog() {
      this.numPages=5
      this.$nextTick(()=>{
        this.$refs.bodyauto.scrollTop = 0
      })
      await materiallearnlog({ applyid: getapplyid(), mid: this.id }).then(
        (res) => {
          if (res.code == 200) {
            res.data.list.map((item) => {
              this.timeNow += item.period;
            });
            if (this.timeNow >= 600) {
              this.overTime = 1;
            } else {
              this.overTime = 0;
            }
            clearInterval(this.Interval);
            this.isTime=0
            this.Interval = setInterval(() => {
              this.isTime++;
              if (this.isTime == 7200) {
                clearInterval(this.Interval);
              }
            }, 1000);
            // this.timeNow=res.data.list[res.data.list.length-1].period
          }
        }
      );
    },
    addexam() {
      clearInterval(this.Interval);
      this.timeNow = 600;
      this.addLog();
    },
  },
  beforeDestroy() {
    // this.val = 1;
    // let obj = {
    //   time: new Date().getSeconds(),
    //   isTime: this.isTime,
    // };
    // setisTime(JSON.stringify(obj));
    // // this.addLog();
    // this.$nextTick(() => {
    //   console.log(this.val, "1111");
    // });
    if(this.isjj){
      this.goback = setTimeout(() => {
        this.addLog();
      }, 1500);
    }
    clearInterval(this.Interval);
  },
};
</script>

<style lang="scss" scoped>
.pdfBox {
  height: calc(100vh - 50px);
  width: 100%;
  position: relative;
  canvas {
    width: 100%;
    height: 100%;
  }
  .border {
    overflow: auto;
    position: absolute;
    bottom: 0;
    // top: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100%;
    height: calc(100% - 90px);
  }
  .pdfTitle {
    position: absolute;
    top: 0;
    width: calc(100%);
    height: calc(90px);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    padding: 24px;
    
  }
}
</style>